/**
 * 
 */
package nl.sportan.samenloop;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;

/**
 * @author bram
 * 
 */
public class XperienceActivity extends Activity {

	private Handler handler;
	private final String consumerKey = getString(R.string.consumer_key);
	private final String consumerSecret = getString(R.string.consumer_secret);
	private SharedPreferences prefs;

	private static final String TOKEN = "token";
	private static final String SECRET = "secret";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		prefs = getPreferences(Context.MODE_PRIVATE);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		handler = new Handler();

		setContentView(R.layout.xperience_layout);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title_bar);
	}

	private void saveToken(AccessToken accessToken) {
		String token = accessToken.getToken();
		String secret = accessToken.getTokenSecret();

		if (token != null && secret != null) {
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(TOKEN, token);
			editor.putString(SECRET, secret);
		}
	}
	
	private AccessToken getAccessToken() {
		
		String token = prefs.getString(TOKEN, null);
		String secret = prefs.getString(SECRET, null);
		
		if (token != null && secret != null) {
			return new AccessToken(token,secret);			
		}
		
		return null;
	}

	
	private void postTweet(String mesg) {
		AccessToken token = getAccessToken();
		
		if (token == null) {
			//Tweet(mesg)
		}
	}
	
	private void Tweet() {
		try {
			Twitter twitter = new TwitterFactory().getInstance();
			twitter.setOAuthConsumer(consumerKey, consumerSecret);
			RequestToken requestToken = twitter.getOAuthRequestToken();
			AccessToken accessToken =  twitter.getOAuthAccessToken(requestToken);

			twitter.verifyCredentials().getId();
			
			saveToken(accessToken);
			
			
			twitter.updateStatus("test");
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void Tweet(AccessToken token) {
		 TwitterFactory factory = new TwitterFactory();
		    //AccessToken accessToken = loadAccessToken(Integer.parseInt(args[0]));
		   // Twitter twitter = factory.getOAuthAuthorizedInstance(consumerKey, consumerSecret, accessToken);
		
		
	}
}
